package com.xwj.validation.common.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xiaowajiang
 * @Date: 2022-03-19 15:17
 * @Description: 校验错误信息返回
 **/
public class ErrorResultUtil {

    /**
     * 获取校验失败的结果
     * @param result
     * @return
     */
    public static Map<String, String> getErrorMap(BindingResult result) {
        return result.getFieldErrors().stream().collect(
                Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (k1, k2) -> k1)
        );
    }

    /**
     * 获取校验失败的结果
     * @param result
     * @return
     */
    public static String getErrorResult(BindingResult result) {
        FieldError error = result.getFieldErrors().stream().findFirst().get();
        return error.getDefaultMessage();
    }

}
